﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Write.Api.Application.Command.MenuCommand;
using MediatR;
using SqlSugar;

namespace B.S.BaseData.Write.Api.Application.CommandHander.MenuCommand
{
    public class DelMenuCommandHander : IRequestHandler<DelMenuCommand, ApiResult<object>>
    {
        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public DelMenuCommandHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<object>> Handle(DelMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> result = new ApiResult<object>();
            result.Code = ApiEnum.删除成功;
            result.Msg = ApiEnum.删除成功.ToString();

            // 获取要删除的菜单
            var menuToDelete = db.Queryable<Menu>().First(x => x.Id == request.Id);
            if (menuToDelete != null)
            {
                // 递归删除子菜单
                await DeleteMenuAndChildren(menuToDelete, cancellationToken);
            }
            else
            {
                result.Code = ApiEnum.删除失败;
                result.Msg = ApiEnum.删除失败.ToString();
            }

            return result;
        }

        private async Task DeleteMenuAndChildren(Menu menu, CancellationToken cancellationToken)
        {
            // 先递归删除子菜单
            var children = db.Queryable<Menu>().Where(x => x.PId == menu.Id).ToList();
            foreach (var child in children)
            {
                await DeleteMenuAndChildren(child, cancellationToken);
            }

            // 再删除当前菜单
            //baseRequsitory.Del(menu);
            await db.Deleteable(menu).ExecuteCommandAsync();
        }
    }
}